package cn.itsource.org.controller;

import cn.itsource.org.domain.User;
import cn.itsource.org.query.UserQuery;
import cn.itsource.org.service.UserService;
import cn.itsource.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    /**
     * 新增或修改
     * @param u
     * @return
     */
    @PutMapping
    public AjaxResult save(@RequestBody User u){
        if (u.getId()==null){
            userService.insert(u);
            return AjaxResult.ok();
        }else {
            userService.updateByPrimaryKeySelective(u);
            return AjaxResult.ok();
        }
    }

    /**
     * 修改
     * @param u
     * @return
     */
    @PostMapping
    public AjaxResult update(@RequestBody User u){
        userService.updateByPrimaryKeySelective(u);
        return AjaxResult.ok();
    }

    /**
     * 分页查询
     * @param userQuery
     * @return
     */
    @PatchMapping
    public AjaxResult pageInfo(@RequestBody UserQuery userQuery){
        try {
            System.out.println(userQuery);
            return AjaxResult.ok(userService.pageInfo(userQuery));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 批量删除
     * @param u
     * @return
     */
    @PatchMapping("/batchDeletion")
    public AjaxResult batchDeletion(@RequestBody List<User> u){

        try {
            userService.deleteAll(u);
            return AjaxResult.ok();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 根据id删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            userService.delete(id);
            return AjaxResult.ok();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 校验用户名
     * @param username
     * @return
     */
    @PostMapping("/check-username")
    public AjaxResult checkUsername(@RequestBody User username){
        Boolean b = userService.existsByUsername(username);

        return AjaxResult.ok(b);
    }
}
